package com.gupaoedu.design.delegate.mvc;

import com.gupaoedu.design.delegate.mvc.controller.MemberAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2018/3/15.
 */
public class DispatchServlet {
    private List<Handler> handlerList = new ArrayList<Handler>();

    public DispatchServlet() {
        initStrategy();
    }

    protected void initStrategy() {
        Class<?> memberActionClass = MemberAction.class;
        try {
            handlerList.add(new Handler()
                    .setController(memberActionClass.newInstance())
                    .setMethod(memberActionClass.getMethod("getMemberAction", new Class[]{String.class}))
                    .setUrl("/web/getMemberAction.json"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doService(HttpServletRequest request, HttpServletResponse response) {
        doDispatch(request, response);
    }

    private void doDispatch(HttpServletRequest request, HttpServletResponse response) {
        String uri = request.getRequestURI();
        Handler handler = null;
        for (Handler h : handlerList) {
            if (uri.equals(h.getUrl())) {
                handler = h;
                break;
            }
        }

        try {
            Object obj = handler.method.invoke(handler.getController(), request.getParameter("mid"));
            //response.getWriter().write(obj);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    class Handler{
        private Object controller;
        private Method method;
        private String url;

        public Object getController() {
            return controller;
        }

        public Handler setController(Object controller) {
            this.controller = controller;
            return this;
        }

        public Method getMethod() {
            return method;
        }

        public Handler setMethod(Method method) {
            this.method = method;
            return this;
        }

        public String getUrl() {
            return url;
        }

        public Handler setUrl(String url) {
            this.url = url;
            return this;
        }
    }
}
